import React, { useState, useEffect, useRef } from "react";
import { View, Text, StyleSheet, Dimensions, Button, Alert, ScrollView, Image } from "react-native";
import { TestSuite, TestCase, Tester } from '@rnoh/testerino';
import type {
    VideoComponentType,
} from "react-native-video/src/fabric/VideoNativeComponent";
import RNCVideo, {  SelectedTrackType,
} from 'react-native-video';


export default function MethodsTextVideo(): JSX.Element {
    const [disableFocus, setDisableFocus] = useState(false)

    return (
        <Tester style={{ flex: 1 }}>
            <ScrollView style={{ flex: 1 }}>
                <TestSuite name="video">
                    {/* 静态方法 */}
                    <TestCase
                        itShould="resume&pause"
                        initialState={false}
                        arrange={({ setState }) => <AddMenuResumeAndPauseTest setState={setState} disableFocus={disableFocus} setDisableFocus={setDisableFocus} />}
                        assert={({ state, expect }) => {
                            expect(state).to.be.true;
                        }}
                    />
                    <TestCase
                        itShould="setVolume"
                        initialState={false}
                        arrange={({ setState }) => <AddSetVolumeTest setState={setState} disableFocus={disableFocus} setDisableFocus={setDisableFocus} />}
                        assert={({ state, expect }) => {
                            expect(state).to.be.true;
                        }}
                    />
                    <TestCase
                        itShould="getCurrentPosition"
                        initialState={false}
                        arrange={({ setState }) => <AddGetCurrentPositionTest setState={setState} disableFocus={disableFocus} setDisableFocus={setDisableFocus} />}
                        assert={({ state, expect }) => {
                            expect(state).to.be.true;
                        }}
                    />
                    <TestCase
                        itShould="selectedAudioTrackTest"
                        initialState={false}
                        arrange={({ setState }) => <AddSelectedAudioTrackTest setState={setState} disableFocus={disableFocus} setDisableFocus={setDisableFocus} />}
                        assert={({ state, expect }) => {
                            expect(state).to.be.true;
                        }}
                    />                    
                    <TestCase
                        itShould="setFullScreen"
                        initialState={false}
                        arrange={({ setState }) => <AddSetFullScreenTest setState={setState} disableFocus={disableFocus} setDisableFocus={setDisableFocus} />}
                        assert={({ state, expect }) => {
                            expect(state).to.be.true;
                        }}
                    />
                    <TestCase
                        itShould="setSource"
                        initialState={false}
                        arrange={({ setState }) => <AddSetSourceTest setState={setState} disableFocus={disableFocus} setDisableFocus={setDisableFocus} />}
                        assert={({ state, expect }) => {
                            expect(state).to.be.true;
                        }}
                    />
                </TestSuite>
            </ScrollView>
        </Tester>

    );
}
// 新增测试用例——静态方法
const AddMenuResumeAndPauseTest = (props: {
    setState: React.Dispatch<React.SetStateAction<boolean>>;
    setDisableFocus: React.Dispatch<React.SetStateAction<boolean>>;
    disableFocus: boolean;
}) => {
    const { disableFocus, setDisableFocus } = props

    const videoref = useRef<React.ElementRef<VideoComponentType>>(null);
    const [timeDuration, setTimeDuration] = useState({
        currentTime: 0,
        playableDuration: 0,
        seekableDuration: 0
    })

    const addRepeatResume = () => {
        videoref?.current?.resume()
    }
    const addRepeatPause = () => {
        videoref?.current?.pause()
    }

    const [show, setShow] = useState(false)
    const addshow = () => {
        setShow(!show)
    }

    return (
        <View style={{
            height: 250,
            width: "100%",
            overflow: 'hidden',
            alignItems: "center"
        }}>
            <Text>currentTime:{timeDuration?.currentTime},playableDuration:{timeDuration?.playableDuration},seekableDuration:{timeDuration?.seekableDuration}</Text>
            <View style={{
                height: 150,
                width: 150,
                overflow: 'hidden',
                justifyContent: 'center',

            }}>
                {show ?
                    <RNCVideo
                        ref={videoref}
                        source={{ uri: "https://971-cn-north-4.cdn-vod.huaweicloud.com/asset/c726f001f9b6c33483dc694002fd5759/09dff810b88651acd29c49cbcec21079.mp4" }}
                        repeat={true}
                        disableFocus={disableFocus}
                        resizeMode={"contain"}
                        style={{ flex: 1 }}
                        onProgress={(currentTime) => {
                            setTimeDuration(currentTime)
                        }}
                    />
                    : null}
            </View>
            <View style={{ marginTop: 20, flexDirection: "row" }}>
                <Button title={"展示video"} onPress={addshow} />
                <Button title={"Resume"} onPress={addRepeatResume} />
                <Button title={"Pause"} onPress={addRepeatPause} />
            </View>
        </View>
    );
}

const AddSetVolumeTest = (props: {
    setState: React.Dispatch<React.SetStateAction<boolean>>;
    setDisableFocus: React.Dispatch<React.SetStateAction<boolean>>;
    disableFocus: boolean;
}) => {
    const { disableFocus, setDisableFocus } = props

    const videoref = useRef<React.ElementRef<VideoComponentType>>(null);
    const [onVolumeChangeData, setOnVolumeChangeData] = useState({
        volume: 0
    })

    const setVolume = () => {
        videoref?.current?.setVolume(0.2)
    }

    const [show, setShow] = useState(false)
    const addshow = () => {
        setShow(!show)
    }
    const onVideoVolumeChange = (volumdata) => {
        console.log("onVideoVolumeChange", volumdata)
        setOnVolumeChangeData(volumdata)
    }

    return (
        <View style={{
            height: 250,
            width: "100%",
            overflow: 'hidden',
            alignItems: "center"
        }}>
            <Text>volume:{onVolumeChangeData?.volume}</Text>
            <View style={{
                height: 150,
                width: 150,
                overflow: 'hidden',
                justifyContent: 'center',

            }}>
                {show ?
                    <RNCVideo
                        ref={videoref}
                        source={{ uri: "https://res.vmallres.com//uomcdn/CN/cms/202210/C75C7E20060F3E909F2998E13C3ABC03.mp4"}}
                        repeat={true}
                        disableFocus={disableFocus}
                        resizeMode={"contain"}
                        style={{ flex: 1 }}
                        onVolumeChange={onVideoVolumeChange}
                    />
                    : null}
            </View>
            <View style={{ marginTop: 20, flexDirection: "row" }}>
                <Button title={"展示video"} onPress={addshow} />
                <Button title={"setVolume 0.2"} onPress={setVolume} />
            </View>
        </View>
    );
}

const AddGetCurrentPositionTest = (props: {
    setState: React.Dispatch<React.SetStateAction<boolean>>;
    setDisableFocus: React.Dispatch<React.SetStateAction<boolean>>;
    disableFocus: boolean;
}) => {
    const { disableFocus, setDisableFocus } = props

    const videoref = useRef<React.ElementRef<VideoComponentType>>(null);
    const [timeDuration, setTimeDuration] = useState({
        currentTime: 0,
        playableDuration: 0,
        seekableDuration: 0
    })
    const [currentPosition, setCurrentPosition] = useState<number | null>(null); // 初始值设为 null
    
    const getCurrentPosition = async () => {
        try {
            if (videoref.current) {
                const position = await videoref.current.getCurrentPosition(); // 等待 Promise 解析
                setCurrentPosition(position); // 设置为实际的数值
            }
        } catch (error) {
            console.error('获取当前位置失败:', error);
            setCurrentPosition(null); // 出错时设为 null
        }
    };

    const [show, setShow] = useState(false)
    const addshow = () => {
        setShow(!show)
    }

    return (
        <View style={{
            height: 250,
            width: "100%",
            overflow: 'hidden',
            alignItems: "center"
        }}>
            <Text>currentTime:{timeDuration?.currentTime},playableDuration:{timeDuration?.playableDuration},seekableDuration:{timeDuration?.seekableDuration}</Text>
            <Text>GetCurrentPosition: {currentPosition !== null ? `${currentPosition} 秒` : '未获取'}</Text>
            <View style={{
                height: 150,
                width: 150,
                overflow: 'hidden',
                justifyContent: 'center',

            }}>
                {show ?
                    <RNCVideo
                        ref={videoref}
                        source={{uri: "https://res.vmallres.com//uomcdn/CN/cms/202210/C75C7E20060F3E909F2998E13C3ABC03.mp4"}}
                        repeat={true}
                        disableFocus={disableFocus}
                        resizeMode={"contain"}
                        style={{ flex: 1 }}
                        onProgress={(currentTime) => {
                            setTimeDuration(currentTime)
                        }}
                    />
                    : null}
            </View>
            <View style={{ marginTop: 20, flexDirection: "row" }}>
                <Button title={"展示video"} onPress={addshow} />
                <Button title={"getCurrentPosition"} onPress={getCurrentPosition} />
            </View>
        </View>
    );
}

const AddSelectedAudioTrackTest = (props: {
    setState: React.Dispatch<React.SetStateAction<boolean>>;
    setDisableFocus: React.Dispatch<React.SetStateAction<boolean>>;
    disableFocus: boolean;
}) => {
    const { disableFocus, setDisableFocus } = props

    const videoRef = useRef<VideoRef>(null);
    const [show, setShow] = useState(false)
    const [duration, setDuration] = useState(0);
    const [audioTracks, setAudioTracks] = useState<AudioTrack[]>([]);
    const [selectedAudioTrack, setSelectedAudioTrack] = useState<SelectedTrack | undefined>(undefined);

    const addshow = () => {
        setShow(!show)
    }

    
    const onAudioTracks = (data: OnAudioTracksData) => {
        console.log('onAudioTracks:', data);
        const currentTracks = data.audioTracks || [];
        setAudioTracks(currentTracks);
        const defaultSelectedTrack = currentTracks.find(track => track.selected);
        if (!defaultSelectedTrack) return;
        setSelectedAudioTrack({
            type: SelectedTrackType.INDEX,
            value: defaultSelectedTrack.index,
        });
        props.setState(true);
    };
    
    const onLoad = (data: OnLoadData) => {
        setDuration(data.duration);
        onAudioTracks(data);
    };

    const switchAudioTracks = () => {
    if (audioTracks.length === 0) return;

    const currentIndex = audioTracks.findIndex(track => {
        if (selectedAudioTrack?.type === SelectedTrackType.INDEX) {
            return track.index === selectedAudioTrack.value;
        }
        return false;
        });
        const nextIndex = (currentIndex + 1) % audioTracks.length;
        const nextTrack = audioTracks[nextIndex];
        setSelectedAudioTrack({
            type: SelectedTrackType.INDEX,
            value: nextTrack.index,
        });
    };


    return (
        <View style={{
            height: 250,
            width: "100%",
            overflow: 'hidden',
            alignItems: "center"
        }}>
            <View style={{
                height: 150,
                width: 150,
                overflow: 'hidden',
                justifyContent: 'center',
            }}>
                {show ?
                    <RNCVideo
                        ref={videoRef}
                        source={{uri:require("../../../assets/multi_track.mp4")} as ReactVideoSource}
                        repeat={true}
                        disableFocus={disableFocus}
                        resizeMode={"contain"}
                        style={{ flex: 1 }}
                        onLoad={onLoad}
                        onAudioTracks={onAudioTracks}
                        selectedAudioTrack={selectedAudioTrack}
                    />
                    : null}
            </View>
            <View style={{ marginTop: 20, flexDirection: "row" }}>
                <Button title={"展示video"} onPress={addshow} />
                <Button title={"切换音频轨道"} onPress={switchAudioTracks} />
            </View>
        </View>
    );
}
const AddSetFullScreenTest = (props: {
    setState: React.Dispatch<React.SetStateAction<boolean>>;
    setDisableFocus: React.Dispatch<React.SetStateAction<boolean>>;
    disableFocus: boolean;
}) => {
    const { disableFocus, setDisableFocus } = props

    const videoref = useRef<React.ElementRef<VideoComponentType>>(null);

    const setFullScreen = () => {
        videoref?.current?.setFullScreen(true)
    }
    const [show, setShow] = useState(false)
    const addshow = () => {
        setShow(!show)
    }
    return (
        <View style={{
            height: 250,
            width: "100%",
            overflow: 'hidden',
            alignItems: "center"
        }}>

            <View style={{
                height: 150,
                width: 150,
                overflow: 'hidden',
                justifyContent: 'center',

            }}>
                {show ?
                    <RNCVideo
                        ref={videoref}
                        source={{ uri: "https://971-cn-north-4.cdn-vod.huaweicloud.com/asset/c726f001f9b6c33483dc694002fd5759/09dff810b88651acd29c49cbcec21079.mp4" }}
                        repeat={true}
                        disableFocus={disableFocus}
                        resizeMode={"contain"}
                        style={{ flex: 1 }}
                    />
                    : null}
            </View>
            <View style={{ marginTop: 20, flexDirection: "row" }}>
                <Button title={"展示video"} onPress={addshow} />
                <Button title={"setFullScreen true"} onPress={setFullScreen} />
            </View>
        </View>
    );
}

const AddSetSourceTest = (props: {
    setState: React.Dispatch<React.SetStateAction<boolean>>;
    setDisableFocus: React.Dispatch<React.SetStateAction<boolean>>;
    disableFocus: boolean;
}) => {
    const { disableFocus, setDisableFocus } = props

    const videoref = useRef<React.ElementRef<VideoComponentType>>(null);

    const SetSource = () => {
        videoref?.current?.setSource({uri: 'https://res.vmallres.com//uomcdn/CN/cms/202210/C75C7E20060F3E909F2998E13C3ABC03.mp4'})
    }
    const [show, setShow] = useState(false)
    const addshow = () => {
        setShow(!show)
    }
    return (
        <View style={{
            height: 250,
            width: "100%",
            overflow: 'hidden',
            alignItems: "center"
        }}>

            <View style={{
                height: 150,
                width: 150,
                overflow: 'hidden',
                justifyContent: 'center',

            }}>
                {show ?
                    <RNCVideo
                        ref={videoref}
                        source={{ uri: "https://971-cn-north-4.cdn-vod.huaweicloud.com/asset/c726f001f9b6c33483dc694002fd5759/09dff810b88651acd29c49cbcec21079.mp4" }}
                        repeat={true}
                        disableFocus={disableFocus}
                        resizeMode={"contain"}
                        style={{ flex: 1 }}
                    />
                    : null}
            </View>
            <View style={{ marginTop: 20, flexDirection: "row" }}>
                <Button title={"展示video"} onPress={addshow} />
                <Button title={"SetSource"} onPress={SetSource} />
            </View>
        </View>
    );
}
